package com.download.zhuaba.Service;

import com.download.zhuaba.Entity.Video;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;

public class VideoService {
    public static ArrayList<Video> getHtml(){
        WebClient webClient = new WebClient(BrowserVersion.FIREFOX_52);//模拟火狐浏览器
        try {

            webClient.setJavaScriptTimeout(5000);
            webClient.getOptions().setUseInsecureSSL(true);//接受任何主机连接 无论是否有有效证书
            webClient.getOptions().setJavaScriptEnabled(true);//设置支持javascript脚本
            webClient.getOptions().setCssEnabled(false);//禁用css支持

            webClient.getOptions().setThrowExceptionOnScriptError(false);//js运行错误时不抛出异常
            webClient.getOptions().setTimeout(100000);//设置连接超时时间
            webClient.getOptions().setDoNotTrackEnabled(false);

            HtmlPage page = webClient.getPage("https://www.bilibili.com/v/popular/rank/all");

            Thread.sleep(3000);
            String xml = page.asXml();
            Document document = Jsoup.parse(xml);//获取html文档
            Elements elements = document.getElementsByClass("info").select("a");
            Elements elements1 = document.getElementsByClass("num");
            Elements elements2 = document.getElementsByClass("data-box");
            int x=0;
            int y=0;
            ArrayList<Video> videos =new ArrayList<>();
            for(int i=0;i<elements1.size();i++){
                Video video =new Video();
                video.setComment(elements2.get(y+1).text());
                video.setNum(elements1.get(i).text());
                video.setPlay(elements2.get(y).text());
                video.setTitle(elements.get(x).toString().replace("target=\"_blank\"","onclick=\"history(this)\" target=\"_blank\""));
                video.setUp(elements.get(x+1).toString().replace("target=\"_blank\"","onclick=\"history(this)\" target=\"_blank\""));
                videos.add(video);
                x=x+2;
                y=y+3;
            }
            return videos;
        } catch (FailingHttpStatusCodeException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } catch (MalformedURLException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }finally {
            webClient.close();
        }
        return null;
    }
}
